package com.shd.edanpei.ui.activity;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Picture;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.shd.edanpei.R;
import com.shd.edanpei.base.BaseActivity;
import com.shd.edanpei.base.data.RxBusCode;
import com.shd.edanpei.base.rxbus.RxBus;
import com.shd.edanpei.common.Constant;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.exception.ResponeThrowable;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.bean.UrlModel;
import com.shd.edanpei.presenter.contract.WebContract;
import com.shd.edanpei.enums.UrlEnum;
import com.shd.edanpei.presenter.WebPresenter;
import com.shd.edanpei.util.ToastUtil;
import com.socks.library.KLog;

import java.io.File;
import java.io.FileOutputStream;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by mc on 2018/3/29.
 * H5页面
 */
public class WebActivity extends BaseActivity<WebPresenter> implements WebContract.WebIView {

    public static final String TITLE = "title";
    public static final String URL = "url";
    public static final String TYPE = "type";

    @BindView(R.id.headline)
    TextView headline;
    @BindView(R.id.web_view)
    WebView webView;

    private final String INVITE = "share";//分享

    private UrlModel mUrlModel;

    private String mTitle;
    private String mUrl;
    private int mType;

    @Override
    protected int setLayout() {
        return R.layout.activity_web;
    }

    @Override
    protected WebPresenter bindPresenter() {
        return new WebPresenter(this);
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        Bundle extras = getIntent().getExtras();
        mTitle = extras.getString(TITLE);
        mUrl = extras.getString(URL);
        mType = extras.getInt(TYPE);

        if (mTitle != null) {
            headline.setText(mTitle);
        }
        if (mUrl != null) {
            setUrl(mUrl);
        } else {
            mPresenter.getUrlInfo(mType);

        }
    }

    private void setUrl(String url) {

        webView.setWebViewClient(new MyWebClient());
        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView webView, int i) {
                super.onProgressChanged(webView, i);
            }

//            @Override
//            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
//                mUploadCallbackAboveL = filePathCallback;
//                take();
//                return true;
//            }

//            //<3.0
//            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
//                mUploadMessage = uploadMsg;
//                take();
//            }

//            //>3.0+
//            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
//                mUploadMessage = uploadMsg;
//                take();
//            }

            //>4.1.1
//            @Override
//            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
//                mUploadMessage = uploadMsg;
//                take();
//            }

        });
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setDomStorageEnabled(false);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 自适应屏幕
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAllowContentAccess(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
//        /**是否自动加载网络图片**/
//        webView.getSettings().setBlockNetworkImage(true);
//        /**是否加载网络资源**/
        webView.getSettings().setBlockNetworkLoads(false);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//        }
//        if (Build.VERSION.SDK_INT >= 19) {
//            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//        }



        webView.loadUrl(url);
        registerForContextMenu(webView);

    }
//
//    @Override
//    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
//        super.onCreateContextMenu(contextMenu, view, contextMenuInfo);
//        final WebView.HitTestResult webViewHitTestResult = webView.getHitTestResult();
//        if (webViewHitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
//                webViewHitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
//            contextMenu.setHeaderTitle("网页中下载图片");
//            contextMenu.add(0, 1, 0, "点击保存")
//                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
//                        @Override
//                        public boolean onMenuItemClick(MenuItem menuItem) {
//                            String DownloadImageURL = webViewHitTestResult.getExtra();
//                            if (URLUtil.isValidUrl(DownloadImageURL)) {
//                                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
//                                request.allowScanningByMediaScanner();
//                                //设置图片的保存路径
//                                request.setDestinationInExternalFilesDir(WebActivity.this, "/img", "/a.png");
//                                DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
//                                downloadManager.enqueue(request);
//                                Toast.makeText(WebActivity.this, "下载成功", Toast.LENGTH_LONG).show();
//                            } else {
//                                Toast.makeText(WebActivity.this, "下载失败", Toast.LENGTH_LONG).show();
//                            }
//                            return false;
//                        }
//                    });
//        }
//    }

    @Override
    protected void initListener() {

    }

    @Override
    public void setUrlInfo(UrlModel model) {
        mUrlModel = model;
        headline.setText(mUrlModel.getTitle());
        setUrl(model.getUrlShow());
    }


    public class MyWebClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains(INVITE)) {
                if (mUrlModel == null) {
                    ApiCreator.getApi().getUrl(UrlEnum.d.getType())
                            .compose(RxTransformer.<UrlModel>errorHandle())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new BaseObserver<UrlModel>() {
                                @Override
                                protected void onSuccess(UrlModel data) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString(Constant.TYPE, Constant.SHARE_URL);
                                    bundle.putParcelable(Constant.DATA, data);
                                    ShareDialogActivity.start(WebActivity.this, bundle);
                                }

                                @Override
                                public void onFailure(ResponeThrowable throwable) {
                                    super.onFailure(throwable);
                                    //加载失败

                                }
                            });

                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.TYPE, Constant.SHARE_URL);
                    bundle.putParcelable(Constant.DATA, mUrlModel);
                    ShareDialogActivity.start(WebActivity.this, bundle);
                }

                return true;
            } else if (url.contains("getmorechance")) {

                RxBus.get().send(RxBusCode.To_PublishFragment);
                finish();
                return true;
            }
            return false;

        }

        @Override
        public void onPageFinished(WebView view, String url) {

            super.onPageFinished(view, url);

//            progressBar.setVisibility(View.GONE);

        }

    }

    private File file;


    private void saveView() {
//        int width = webView.getWidth();
//        int height = webView.getHeight();
//        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
//        Canvas canvas = new Canvas(bitmap);
//        canvas.drawColor(Color.WHITE);
//        webView.draw(canvas);
//
//
//        String path = Environment.getExternalStorageDirectory().getPath() + "/DCIM/";
//        file = new File(path, "haha.jpg");
//        try {
//            FileOutputStream fileOutputStream = new FileOutputStream(file);
//            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fileOutputStream);
//            fileOutputStream.flush();
//            fileOutputStream.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            bitmap.recycle();
//        }

//        Picture picture = webView.capturePicture();
//        Bitmap b = Bitmap.createBitmap(
//                picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
//        Canvas c = new Canvas(b);
//        picture.draw(c);
//        file = new File("/sdcard/" + "page.jpg");
//        if(file.exists()){
//            file.delete();
//        }
//        FileOutputStream fos = null;
//        try {
//            fos = new FileOutputStream(file.getAbsoluteFile());
//            if (fos != null) {
//                b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
//                fos.close();
//                Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            Toast.makeText(getApplicationContext(), "保存失败", Toast.LENGTH_SHORT).show();
//        }

    }

    @OnClick(R.id.iv_headline_back)
    public void onViewClicked() {
        finish();
//        saveView();
//        UrlModel urlModel = new UrlModel();
//        urlModel.setPicFile(file.getPath());
//        Bundle bundle = new Bundle();
//        bundle.putString(Constant.TYPE, Constant.SHARE_PIC);
//        bundle.putParcelable(Constant.DATA, urlModel);
//        ShareActivity.start(this, bundle);
    }


    public static void start(Context context, String titile, String url, int type) {
        Bundle bundle = new Bundle();
        bundle.putString(TITLE, titile);
        bundle.putString(URL, url);
        bundle.putInt(TYPE, type);
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }
}
